package com.eds.service;

import com.eds.dao.RedisDao;
import com.eds.exception.BusException;
import com.eds.log.LogUtil;
import com.eds.pojo.CodeEnum;
import com.eds.utils.CaptchaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CaptchaService {
    @Autowired
    private RedisDao<String> redisDao;

    public CaptchaUtils.Captcha generateCaptcha(String id) {
        // 生成验证码
        CaptchaUtils.Captcha captchaResult = CaptchaUtils.generateCaptcha();

        // 存进Redis，设置过期时间为5分钟
        redisDao.set("Captcha:Code:" + id, captchaResult.getCode(), 2, TimeUnit.MINUTES);
        LogUtil.methodCall(CaptchaService.class, "Generated captcha code =", captchaResult.getCode());
        return captchaResult;
    }

    public boolean verifyCaptcha(String id, String code) {
        String redisCode = redisDao.get("Captcha:Code:" + id);

        if (redisCode == null || !redisCode.equalsIgnoreCase(code)) { // 使用equalsIgnoreCase忽略大小写差异
            throw new BusException(CodeEnum.CAPTCHA_VERIFY_ERROR.getCode(), CodeEnum.CAPTCHA_VERIFY_ERROR.getMessage());
        }
        // 验证成功后删除验证码
        redisDao.del("Captcha:Code:" + id);
        return true;
    }
}